package shelve;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;

import static java.lang.System.out;

@WebServlet(name = "Servlet", value = "/Servlet")
public class Servlet<JsonObject> extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    //提供JDBC连接的URL
    static final String DB_URL = "jdbc:mysql://localhost:3306/011? userUnicode = true&characterEocoding = utf8&useSSL=FALSE&serverTimezone=UTC&allowPblicKeyRetrieval=true\" ;" ;
    static final String USER = "root";
    static final String PASS = "5838380";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //fastjson前后端传参
        /*
         *获得数据：
         *jsonObject.getString();
         */
//数据转换成json字符串
//String jsonString02 = JsonObject.toJsonString(Object o);
        InputStreamReader inputStreamReader = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
        StringBuilder str = new StringBuilder();
        int respInt = inputStreamReader.read();
        while (respInt != -1) {
            str.append((char) respInt);
            respInt = inputStreamReader.read();
        }

        String jsonString = String.valueOf(str);
        DateFormat JsonObject = null;
        try {
            JsonObject jsonObject = (JsonObject) JsonObject.parseObject(jsonString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //连接数据库
        //打开一个连接
        try {
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            out.println(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //执行查询用户名和密码
        try {
            stmt = conn.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //更新图书信息
        String sql;
        sql = "update information set bookname=?,author=?,kind=?,status =?  where author =? and kind=?;";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, "c++");
            preparedStatement.setString(2, "大牛2");
            preparedStatement.setString(3, "C2");
            preparedStatement.setString(4, "未借出");
            preparedStatement.setString(5, "大牛");
            preparedStatement.setString(6, "c");
            int i = preparedStatement.executeUpdate();


            //判断sql语句是否执行成功
            if (i >= 1) {
                out.println("sql执行成功");
                out.println("执行条数：" + i);
            } else {
                out.println("sql失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //图书上架
        sql="insert into sta(bookname, author, kind ,status) values ('c++', '大牛', 'C', '未借出');";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        sql = "INSERT INTO sta (bookname, kind , author,status) VALUES('a','0','0','0')";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //图书下架
        sql = "DELETE FROM sta WHERE bookname='a';";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //过滤器
    public class OriginFitlerTwice implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            Filter.super.init(filterConfig);
        }

        @Override
        public void destroy() {
            Filter.super.destroy();
        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

            //强制类型转换
            HttpServletRequest request=(HttpServletRequest)servletRequest;
            HttpServletResponse response=(HttpServletResponse) servletResponse;

            //获取请Origin请求头
            String origins=request.getHeader("Origin");
            //设置response响应头
            response.setHeader("Access-Control-Allow-Origin",origins);
            //设置所有自定义头
            String headers=request.getHeader("Access-Control-Request-Headers");
            response.setHeader("Access-Control-Allow-headers",headers);
            response.setHeader("Access-Control-Expose-headers",headers);
            //设置运行经济跨域的请求方法
            response.setHeader("Access-Control-Allow-Methods","*");
            //预检请求缓存事件,单位:秒
            response.setHeader("Access-Control-Max-Age","3600");
            //允许客户端发送Cookie
            response.setHeader("Access-Control-Allow-Credentials","true");

            //放置到过滤链上,
            filterChain.doFilter(request,response);

            //给个提示
            System.out.println("跨域过滤器已执行");
        }
    }
}

